﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using Guoc.DAL.Common;
using NHibernate;
namespace Guoc.DAL.AOPFilter
{
    /// <summary>
    /// 事务过滤
    /// </summary>
   public class TransactionFilter: AopFilter
    {
       //使用Nhibernate 事务
       ISession currentSession;
       ITransaction itran;


       //1 调用基类构造函数，传递消息
       public TransactionFilter(IMessageSink nextMsg)
           : base(nextMsg)
       { }

       
       //2 重写切面编程方法

       public override void OnExecuting(IMessage msg)
       {
           //开启事务
           currentSession = NhibernateHelper.GetCurrentSession();

           itran=currentSession.BeginTransaction();

       }

       public override void OnExecuted(IMessage msg)
       {
           if (currentSession == null || !itran.IsActive)
           {
               return;
           }
           IMethodReturnMessage returnMsg = (IMethodReturnMessage)msg;
           //判断是否有异常存在
           if (returnMsg.Exception == null)
           {
               itran.Commit(); //提交事务
           }
           else
           {
               itran.Rollback(); //回滚事务
           }  
       }
    }
}
